package tcp

import (
	"gomonitor-server/src/mylog"
	"gomonitor-server/src/tcp/message"
	"net"
)

func processMessage(msgHandler *message.MessageHandler, msgFrom byte, bufferLen int, buffer []byte, bufferPool *[]byte, conn net.Conn) bool {
	mylog.Logger.Debugf("接收连接%s的消息，消息实际长度%d,消息长度%d,缓冲池中的长度%d", conn.RemoteAddr().String(), bufferLen, len(buffer), len(*bufferPool))

	result := msgHandler.ReceiveMessage(msgFrom, bufferLen, buffer, bufferPool, conn)
	if result {
		//没有断包，可能粘包
		bufferPoolLen := len(*bufferPool)
		mylog.Logger.Debugf("连接%s的缓冲池中的数据长度是:%d", conn.RemoteAddr().String(), bufferPoolLen)
		if bufferPoolLen != 0 {
			//粘包
			msgBuffer := make([]byte, len(*bufferPool))
			for i := range msgBuffer {
				msgBuffer[i] = (*bufferPool)[i]
			}
			//清空缓冲池
			*bufferPool = []byte{}
			return processMessage(msgHandler, msgFrom, bufferPoolLen, msgBuffer, bufferPool, conn)
		} else {
			mylog.Logger.Debugf("数据包正常处理完成,清空缓冲池，缓冲池之前长度:%d", len(*bufferPool))
			//数据包正常处理完成
			*bufferPool = []byte{}
			return true
		}
	} else {
		//短包
		mylog.Logger.Debugf("连接%s断包重新读取..之前缓冲区长度:%d", conn.RemoteAddr().String(), len(*bufferPool))
		n, err := conn.Read(buffer)
		if err != nil {
			mylog.Logger.Errorf("连接%s断包重新读取失败,清空缓冲区", conn.RemoteAddr().String())
			*bufferPool = []byte{}
			return true
		} else {
			mylog.Logger.Debugf("连接%s断包重新读取成功..之前缓冲区长度:%d，重新读取到的长度:%d", conn.RemoteAddr().String(), len(*bufferPool), n)
		}
		if n == 0 {
			return true
		}
		//附加之前数据
		*bufferPool = append(*bufferPool, buffer[:n]...)
		msgBuffer := make([]byte, len(*bufferPool))
		for i := range msgBuffer {
			msgBuffer[i] = (*bufferPool)[i]
		}
		//清空缓冲池
		*bufferPool = []byte{}
		return processMessage(msgHandler, msgFrom, len(msgBuffer), msgBuffer, bufferPool, conn)
	}
}
